// String 扩展

import Foundation

extension String {
    
    /// 通过下标来检索/替换字符串
    ///
    /// - Parameter range: 需要检测的Range<Int>
    /// eg.
    /// var str = "abcdefg"
    /// let rst = str[1..<3] // 结果：rst == "bc"; str = "abcdefg"
    /// str[1..<3] = "MMMM" // 结果：str == "aMMMMdefg"
    ///
    subscript (range: Range<Int>) -> String {
    
        get {
            // 数据无效
            let invalid = range.lowerBound < 0 || range.upperBound > self.count
            assert(!invalid , "无效下标")
            let startIndex = self.index(self.startIndex, offsetBy: range.lowerBound)
            let endIndex = self.index(self.startIndex, offsetBy: range.upperBound)
            return String(self[startIndex..<endIndex])
        }
        set {
            let startIndex = self.index(self.startIndex, offsetBy: range.lowerBound)
            let endIndex = self.index(self.startIndex, offsetBy: range.upperBound)
            let strRange = startIndex..<endIndex
            self.replaceSubrange(strRange, with: newValue)
        }
    }
    subscript (index: Int) -> String {
        get { return self[index..<index+1] }
        set { self[index..<index+1] = newValue }
    }
}

// MARK: - 正则
extension String {
    public func matchString(_ pattern: String) -> Bool {
        let regularExp = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive)
        
        if let matches = regularExp?.matches(in: self, options: .anchored, range: NSMakeRange(0, self.lengthOfBytes(using: String.Encoding.utf8))) {
            return matches.count > 0
        } else {
            return false
        }
    }
}
